package com.ruoyi.hr.personalFile.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.hr.personalFile.domain.HrPersonnelFile;
import com.ruoyi.hr.personalFile.mapper.HrPersonnelFileMapper;
import com.ruoyi.hr.personalFile.service.IHrPersonnelFileService;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.redis.RedisService;
import com.ruoyi.system.cache.user.UserCacheService;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.shiro.authc.credential.PasswordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.text.Convert;

/**
 * 人事档案Service业务层处理
 *
 * @author xzshan
 * @date 2020-07-15
 */
@Service
public class HrPersonnelFileServiceImpl implements IHrPersonnelFileService {
  @Autowired
  private HrPersonnelFileMapper hrPersonnelFileMapper;
  @Autowired
  private RedisService redisService;
  @Autowired
  private UserCacheService userCacheService;
  @Autowired
  private SysPasswordService passwordService;

  /**
   * 查询人事档案
   *
   * @param id 人事档案ID
   * @return 人事档案
   */
  @Override
  public HrPersonnelFile selectHrPersonnelFileById(Long id) {
    return hrPersonnelFileMapper.selectHrPersonnelFileById(id);
  }

  @Override
  public HrPersonnelFile selectByNameAndPhone(String name,String phone){
    Map<String,String>map=new HashMap<>();
    map.put("name",name);
    map.put("phone",phone);
    return hrPersonnelFileMapper.selectByNameAndPhone(map);
  }

  @Override
  public HrPersonnelFile selectHrPersonnelFileBySysUserId(Long sysUserId) {
    return hrPersonnelFileMapper.selectHrPersonnelFileBySysUserId(sysUserId);
  }

  /**
   * 查询人事档案列表
   *
   * @param hrPersonnelFile 人事档案
   * @return 人事档案
   */
  @Override
  public List<HrPersonnelFile> selectHrPersonnelFileList(HrPersonnelFile hrPersonnelFile) {
    return hrPersonnelFileMapper.selectHrPersonnelFileList(hrPersonnelFile);
  }

  /**
   * 新增人事档案
   *
   * @param hrPersonnelFile 人事档案
   * @return 结果
   */
  @Override
  public int insertHrPersonnelFile(HrPersonnelFile hrPersonnelFile) {
    //生成工号
    handlePersonCode(hrPersonnelFile);
    //生成用户信息
   int rs= autoCreateUser(hrPersonnelFile);
   if(rs < 0){
     return rs;
   }
    return hrPersonnelFileMapper.insertHrPersonnelFile(hrPersonnelFile);
  }

  public int autoCreateUser(HrPersonnelFile hrPersonnelFile) {
    String phone = hrPersonnelFile.getPhone();
    if(StringUtils.isEmpty(hrPersonnelFile.getCode()) || StringUtils.isEmpty(phone)){
      return -1;
    }
//    if(hrPersonnelFile.getPostId() ==null || hrPersonnelFile.getDeptId() ==null){
//
//      return;
//    }
    SysUser sysUser = new SysUser();
    String name = hrPersonnelFile.getName();
    String code = hrPersonnelFile.getCode();
    sysUser.setPhonenumber(hrPersonnelFile.getPhone());
    SysUser dbUser = userService.selectUserByLoginName(phone);
    if (dbUser != null) {
      //该账户已存在，判断该账户的code
      if (StringUtils.isEmpty(dbUser.getUserCode())) {
        dbUser.setUserCode(code);
        userService.updateUserInfo(dbUser);
        return 0;
      }else {
        return 0;
      }
    }
    sysUser.setLoginName(phone);
    sysUser.setUserCode(code);
    sysUser.setUserName(name);
    sysUser.setSalt(ShiroUtils.randomSalt());
    sysUser.setPassword(passwordService.encryptPassword(phone, Md5Utils.hash("123456"), sysUser.getSalt()));
    sysUser.setCreateBy("hrPersonelExcelImport");
    sysUser.setDeptId(hrPersonnelFile.getDeptId());
    sysUser.setPostIds(new Long[]{hrPersonnelFile.getPostId()});
    userService.insertUser(sysUser);
    return 1;
  }

  @Autowired
  private ISysDeptService deptService;
  @Autowired
  private ISysPostService postService;

  @Autowired
  private ISysUserService userService;

  private void handlePersonCode(HrPersonnelFile hrPersonnelFile) {
    StringBuilder sb = new StringBuilder();
    Long deptId = hrPersonnelFile.getDeptId();

    SysDept sysDept = deptService.selectDeptById(deptId);
    if (sysDept == null) {
      sb.append("6");
    } else {
      String outside = sysDept.getOutside();
      if (outside != null && outside.equalsIgnoreCase("1")) {
        sb.append("8");//外联是8开头
      } else {
        sb.append("6");
      }
    }

    Long postId = hrPersonnelFile.getPostId();
    if (postId != null) {
      SysPost sysPost = postService.selectPostById(postId);
      if (null != sysPost) {
        String postCode = sysPost.getPostCode();
        sb.append(postCode);
      } else {
        throw new RuntimeException("岗位信息异常");
      }
    }else {
      if(!StringUtils.isEmpty(hrPersonnelFile.getPost())){
        Map<String, Object> map = postService.selectPostByName(hrPersonnelFile.getPost());
        if(map == null){return;}
        String postCode = String.valueOf(map.get("post_code"));
        if(StringUtils.isEmpty(postCode)){
          return ;
        }
        hrPersonnelFile.setPostId(Long.parseLong(String.valueOf(map.get("post_id"))));
        sb.append(postCode);
      }else {
        return;
      }
    }
    String userCode = getUserCode();
    sb.append(userCode);
    hrPersonnelFile.setCode(sb.toString());
    sb = null;
  }

  public String getUserCode() {
    String userCode = userCacheService.getNextUserCode(4);
    redisService.incr("lastUserCode", 1);
    if (StringUtils.isEmpty(userCode)) {
      String rs = getUserCode();
      if (StringUtils.isEmpty(userCode)) {
        rs = getUserCode();
        return rs;
      }
    }
    return userCode;
  }

  /**
   * 修改人事档案
   *
   * @param hrPersonnelFile 人事档案
   * @return 结果
   */
  @Override
  public int updateHrPersonnelFile(HrPersonnelFile hrPersonnelFile) {
    Long newUserId = hrPersonnelFile.getSysUserId();
    Long id = hrPersonnelFile.getId();
    Long oldUserId = selectHrPersonnelFileById(id).getSysUserId();
    //更新账户工号信息，解绑工号，绑定工号
    if (newUserId != null) {
      if (oldUserId != null && newUserId != oldUserId) {//旧解除，新绑定
        SysUser oldUser = new SysUser();
        oldUser.setUserId(oldUserId);
        userService.updateUserCode(oldUser);

        SysUser newUser = new SysUser();
        newUser.setUserId(newUserId);
        newUser.setUserCode(hrPersonnelFile.getCode());
        userService.updateUserInfo(newUser);
      }
    } else {
      if (oldUserId != null) {
        SysUser oldUser = new SysUser();
        oldUser.setUserId(oldUserId);
        userService.updateUserCode(oldUser);
      }
    }
    return hrPersonnelFileMapper.updateHrPersonnelFile(hrPersonnelFile);
  }

  @Override
  public int updateHrPersonnelFileInfo(HrPersonnelFile hrPersonnelFile) {
    return hrPersonnelFileMapper.updateHrPersonnelFile(hrPersonnelFile);
  }

  /**
   * 删除人事档案对象
   *
   * @param ids 需要删除的数据ID
   * @return 结果
   */
  @Override
  public int deleteHrPersonnelFileByIds(String ids) {
    return hrPersonnelFileMapper.deleteHrPersonnelFileByIds(Convert.toStrArray(ids));
  }

  /**
   * 删除人事档案信息
   *
   * @param id 人事档案ID
   * @return 结果
   */
  @Override
  public int deleteHrPersonnelFileById(Long id) {
    return hrPersonnelFileMapper.deleteHrPersonnelFileById(id);
  }

  @Override
  public String importPerson(List<HrPersonnelFile> personnelFiles, boolean updateSupport, String operName) {
    if (StringUtils.isNull(personnelFiles) || personnelFiles.size() == 0) {
      throw new BusinessException("导入数据不能为空！");
    }

    int successNum = 0;
    int failureNum = 0;
    StringBuilder successMsg = new StringBuilder();
    StringBuilder failureMsg = new StringBuilder();
    for (HrPersonnelFile personnelFile : personnelFiles) {
      try {
        if (StringUtils.isNull(personnelFile.getDeptId()) || personnelFile.getPost() == null) {
          throw new BusinessException("部门或者岗位不能为空");
        }
        if (StringUtils.isNull(personnelFile.getName()) || personnelFile.getPhone() == null) {
          throw new BusinessException("姓名或手机号不能为空");
        }
        HrPersonnelFile tmp = selectByNameAndPhone(personnelFile.getName(), personnelFile.getPhone());
        if(tmp !=null){
          throw new BusinessException(personnelFile.getName()+"已存在该用户");
        }
        int rs = insertHrPersonnelFile(personnelFile);
        successNum++;
        successMsg.append("<br/>" + successNum + "员工" + personnelFile.getName() + " 导入成功");

      } catch (Exception e) {

        failureNum++;
        String msg = "<br/>" + failureNum + "、员工 " + personnelFile.getName() + " 导入失败：";
        failureMsg.append(msg + e.getMessage());
        e.printStackTrace();
      }
    }
    if (failureNum > 0) {
      failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
      throw new BusinessException(failureMsg.toString());
    } else {
      successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
    }
    return successMsg.toString();
  }

  @Override
  public void check(Long id, String suspendState) {
    Map<String,Object>map=new HashMap<>();
    map.put("id",id);
    map.put("suspendState",suspendState);
    hrPersonnelFileMapper.check(map);
  }
}
